package org.jeecg.modules.hc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.hc.entity.*;
import org.jeecg.modules.hc.enums.HcBusinessStateEnum;
import org.jeecg.modules.hc.enums.HcDeliveryStatusEnum;
import org.jeecg.modules.hc.enums.HcStoreStatusEnum;
import org.jeecg.modules.hc.enums.HcUpFlagEnum;
import org.jeecg.modules.hc.mapper.HcAddressMerchantRelationMapper;
import org.jeecg.modules.hc.mapper.HcCommodityMapper;
import org.jeecg.modules.hc.mapper.HcMerchantMapper;
import org.jeecg.modules.hc.mapper.HcSiteRelationMapper;
import org.jeecg.modules.hc.service.*;
import org.jeecg.modules.hc.utils.HcUtils;
import org.jeecg.modules.hc.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description: 商户
 * @Author: jeecg-boot
 * @Date: 2022-12-13
 * @Version: V1.0
 */
@Service
@Slf4j
public class HcMerchantServiceImpl extends ServiceImpl<HcMerchantMapper, HcMerchant> implements IHcMerchantService {

    @Resource
    private HcMerchantMapper hcMerchantMapper;

    @Resource
    private HcCommodityMapper hcCommodityMapper;

    @Autowired
    private IHcCommodityService hcCommodityService;

    @Autowired
    private IHcMainCategoriesService hcMainCategoriesService;

    @Autowired
    private IHcMainRelationService hcMainRelationService;

    @Autowired
    private IHcSiteService hcSiteService;

    @Autowired
    private IHcSiteAddressDetailsService hcSiteAddressDetailsService;

    @Autowired
    private IHcSiteRelationService hcSiteRelationService;

    @Resource
    private HcSiteRelationMapper hcSiteRelationMapper;

    @Lazy
    @Autowired
    private IHcShoppingCartService hcShoppingCartService;

    @Autowired
    private IHcMerchantCommissionService hcMerchantCommissionService;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private WxMpService mpService;

    @Autowired
    private HcAddressMerchantRelationMapper addressMerchantRelationMapper;


    @Value("${wx.pay.privateKeyPath}")
    private String privatekeypath ;
//    @Value("${wx.pay.appId}")
//    private String appId;
//    @Value("${wx.pay.mchId}")
//    private String mchid;
//    @Value("${wx.pay.certSerialNo}")
//    private String wechatPayserialNo;

    @Override
    public void setOpenId(String code, String userId) throws WxErrorException {

        if (StringUtils.isBlank(code)) {
            throw new JeecgBootException("code empty");
        }
        log.info("setOpenId code:{}", code);
        WxOAuth2AccessToken accessToken = mpService.getOAuth2Service().getAccessToken(code);

        if (accessToken == null || StringUtils.isEmpty(accessToken.getOpenId())) {
            throw new JeecgBootException("获取商户信息失败");
        }
        this.updateById(new HcMerchant().setId(userId).setOpenId(accessToken.getOpenId()));

    }

    public void syncCommodityToRedis() {
//        List<HcCommodity> hcCommodityList = hcCommodityService.list();
//        System.out.println("hcCommodityList size= " + hcCommodityList.size());
//        List<HcMerchantCommission> hcMerchantCommissionList = hcMerchantCommissionService.list();
//        System.out.println("hcMerchantCommissionList size= " + hcMerchantCommissionList.size());
//
//        int i = 0;
//        for (HcCommodity hcCommodity : hcCommodityList) {
//            for (HcMerchantCommission hcMerchantCommission : hcMerchantCommissionList) {
//                hcCommodityService.setInformation(hcCommodity, hcMerchantCommission);
//                redisUtil.set(RedisConstant.HC_COMMODITY + hcCommodity.getId() + "_" + hcMerchantCommission.getId(), JSON.toJSONString(hcCommodity));
//                i++;
//            }
//        }
//
//        System.out.println("syncCommodityToRedis count: " + i);
    }

    public HcMerchant login(String phone, String pass) {
        HcMerchant hcMerchant = this.getOne(new LambdaQueryWrapper<HcMerchant>().eq(HcMerchant::getLoginAccount, phone));

        if (hcMerchant == null) {
            throw new JeecgBootException("手机号不存在");
        }

        if (!hcMerchant.getPass().equals(pass)) {
            throw new JeecgBootException("密码错误");
        }

        String token = this.generateToken(hcMerchant.getLoginAccount());
        HcMerchant result = new HcMerchant();
        result.setToken(token);
        result.setOpenId(hcMerchant.getOpenId());
        return result;
    }

    public HcMerchant getTokenById(String id) {
        HcMerchant hcMerchant = this.getById(id);

        if (hcMerchant == null) {
            throw new JeecgBootException("数据不存在");
        }

        String token = this.generateToken(hcMerchant.getLoginAccount());
        HcMerchant result = new HcMerchant();
        result.setToken(token);
        return result;
    }

    public String generateToken(String account) {
        // 生成token
        String token = JwtUtil.sign(CommonConstant.HC_MERCHANT_LOGIN_TOKEN + account, CommonConstant.HC_MERCHANT_LOGIN_PASSWORD);

        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);

        return token;
    }

    @Override
    public void setInformation(HcMerchant param) {
        HcMainRelation hcMainRelation = hcMainRelationService.getOne(new LambdaQueryWrapper<HcMainRelation>()
                .eq(HcMainRelation::getMerchantId, param.getId())
                .last(" limit 1 ")
        );

        if (hcMainRelation != null) {
            param.setMainCategoriesId(hcMainRelation.getMainCategoriesId());
        }

        List<HcSiteRelation> siteRelationList = hcSiteRelationMapper.getListByMerchantId(param.getId());

        if (!CollectionUtils.isEmpty(siteRelationList)) {
            List<String> collect = siteRelationList.stream().map(HcSiteRelation::getSiteId).collect(Collectors.toList());
            param.setSiteId(String.join(",", collect));

            List<String> siteNameList = hcSiteService.listObjs(new LambdaQueryWrapper<HcSite>()
                    .select(HcSite::getName)
                    .in(HcSite::getId, collect), Object::toString
            );

            param.setSiteName(String.join(",", siteNameList));

            HcMerchant hcMerchant = hcMerchantMapper.selectById(param.getId());

            //获取站点对应大厦的供餐时间和开启情况
            siteRelationList.forEach(s -> {
                List<HcAddressMerchantRelation> addressMerchantRelations = new ArrayList<>();
                //获取所有的大厦
                List<HcSiteAddressDetails> hcSiteAddressDetails = hcSiteAddressDetailsService.list(new LambdaQueryWrapper<HcSiteAddressDetails>().eq(HcSiteAddressDetails::getSiteId, s.getSiteId()));
                if (!CollectionUtils.isEmpty(hcSiteAddressDetails)){
                    String businessHours = hcMerchant.getBusinessHours();
                    JSONArray objects = JSONArray.parseArray(businessHours);
                    String startTime = objects.getJSONObject(0).getString("startTime");
                    String endTime = objects.getJSONObject(0).getString("endTime");
                    hcSiteAddressDetails.forEach( h -> {
                        HcAddressMerchantRelation hcAddressMerchantRelation = addressMerchantRelationMapper.selectOne(new LambdaQueryWrapper<HcAddressMerchantRelation>()
                                .eq(HcAddressMerchantRelation::getMerchantId, hcMerchant.getId()).eq(HcAddressMerchantRelation::getAddressDetailsId, h.getId()));
                        if (null == hcAddressMerchantRelation){
                            hcAddressMerchantRelation = new HcAddressMerchantRelation();
                            hcAddressMerchantRelation.setMerchantId(hcMerchant.getId());
                            hcAddressMerchantRelation.setAddressDetailsId(h.getId());
                            hcAddressMerchantRelation.setIsOpen("true");
                            hcAddressMerchantRelation.setProvideStartTime(startTime);
                            hcAddressMerchantRelation.setProvideEndTime(endTime);
                            addressMerchantRelationMapper.insert(hcAddressMerchantRelation);
                        }
                        hcAddressMerchantRelation.setAddressDetailsName(h.getAddressName());
                        addressMerchantRelations.add(hcAddressMerchantRelation);
                    });
                }
                s.setAddressMerchantRelations(addressMerchantRelations);
            });

        }

        param.setHcSiteRelationList(siteRelationList);
        this.checkBusinessState(param);
    }

    public void checkBusinessState(HcMerchant param) {
        try {
            JSONArray jsonArray = JSON.parseArray(param.getBusinessHours());
            HcBusinessStateEnum businessStateEnum = HcBusinessStateEnum.NO;

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                String startTime = jsonObject.getString("startTime");
                String endTime = jsonObject.getString("endTime");

                boolean nowBetweenHHmmss = HcUtils.nowBetweenHHmmss(startTime, endTime);

                if (nowBetweenHHmmss) {
                    businessStateEnum = HcBusinessStateEnum.YES;
                }
            }

            //判断有id，并且营业状态不是管理员打烊，并且营业状态与当前状态不符 则更新营业状态
            if (StringUtils.isNotBlank(param.getId()) && param.getBusinessState() != HcBusinessStateEnum.NO_ADMIN && param.getBusinessState() != businessStateEnum) {
                this.updateById(new HcMerchant().setId(param.getId()).setBusinessState(businessStateEnum));
                param.setBusinessState(businessStateEnum);
            }
        } catch (Exception e) {
            log.info(JSON.toJSONString(param));
            e.printStackTrace();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void edit(HcMerchant param) {
        String mainCategoriesId = param.getMainCategoriesId();
        HcMainCategories hcMainCategories = hcMainCategoriesService.getById(mainCategoriesId);

        if (hcMainCategories == null) {
            throw new JeecgBootException("主营品类不存在");
        }

        //将商户相关联的大厦的营业时间修改一致
        String businessHours = param.getBusinessHours();
        JSONArray objects = JSONArray.parseArray(businessHours);
        String startTime = objects.getJSONObject(0).getString("startTime");
        String endTime = objects.getJSONObject(0).getString("endTime");

        HcMerchant hcMerchant = this.getById(param.getId());
        String businessHours1 = hcMerchant.getBusinessHours();
        JSONArray objects1 = JSONArray.parseArray(businessHours1);
        String updateStartTime = objects1.getJSONObject(0).getString("startTime");
        String updateEndTime = objects1.getJSONObject(0).getString("endTime");
        if ( !startTime.equals(updateStartTime) || !endTime.equals(updateEndTime)){
            List<HcSiteRelation> hcSiteRelationList = param.getHcSiteRelationList();
            if (!CollectionUtils.isEmpty(hcSiteRelationList)){
                hcSiteRelationList.forEach(h -> {
                    List<HcAddressMerchantRelation> addressMerchantRelations = h.getAddressMerchantRelations();
                    if (!CollectionUtils.isEmpty(addressMerchantRelations)){
                        addressMerchantRelations.forEach(a -> {
                            if (a.getProvideStartTime().equals(updateStartTime) && a.getProvideEndTime().equals(updateEndTime)){
                                a.setProvideStartTime(startTime);
                                a.setProvideEndTime(endTime);
                                addressMerchantRelationMapper.updateById(a);
                            }
                        });
                    }
                });
            }
        }



        this.updateById(param);

        hcMainRelationService.remove(new LambdaQueryWrapper<HcMainRelation>()
                .eq(HcMainRelation::getMerchantId, param.getId())
        );
        hcMainRelationService.save(new HcMainRelation().setMerchantId(param.getId()).setMainCategoriesId(hcMainCategories.getId()));

        hcSiteRelationService.remove(new LambdaQueryWrapper<HcSiteRelation>()
                .eq(HcSiteRelation::getMerchantId, param.getId())
        );

        saveSiteRelation(param);

        updateAddressMerchantRelation(param);
    }

    //更新大厦与商户的关系
    @Transactional(rollbackFor = Exception.class)
    public void updateAddressMerchantRelation(HcMerchant param){
        List<HcSiteRelation> hcSiteRelationList = param.getHcSiteRelationList();
        if (!CollectionUtils.isEmpty(hcSiteRelationList)){
            hcSiteRelationList.forEach( h -> {
                List<HcAddressMerchantRelation> addressMerchantRelations = h.getAddressMerchantRelations();
                if (!CollectionUtils.isEmpty(addressMerchantRelations)){
                    addressMerchantRelations.forEach(a -> {
                        addressMerchantRelationMapper.updateById(a);
                    });
                }
            });
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(HcMerchant param) {
        String mainCategoriesId = param.getMainCategoriesId();
        HcMainCategories hcMainCategories = hcMainCategoriesService.getById(mainCategoriesId);

        if (hcMainCategories == null) {
            throw new JeecgBootException("主营品类不存在");
        }

        param.setStoreStatus(HcStoreStatusEnum.NO);
        param.setDeliveryStatus(HcDeliveryStatusEnum.NO);
        this.save(param);

        hcMainRelationService.save(new HcMainRelation().setMerchantId(param.getId()).setMainCategoriesId(hcMainCategories.getId()));

        saveSiteRelation(param);
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveSiteRelation(HcMerchant param) {
        if (!CollectionUtils.isEmpty(param.getHcSiteRelationList())) {
            for (HcSiteRelation hcSiteRelation : param.getHcSiteRelationList()) {
                HcSite hcSite = hcSiteService.getById(hcSiteRelation.getSiteId());

                if (hcSite == null) {
                    throw new JeecgBootException("站点不存在");
                }

                hcSiteRelationService.save(new HcSiteRelation()
                        .setMerchantId(param.getId())
                        .setSiteId(hcSite.getId())
                        .setSort(hcSiteRelation.getSort())
                );
            }
        }
    }

    public List<HcCommodity> queryCommodityByMerchantId(HcMerchant param) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        LambdaQueryWrapper<HcCommodity> queryWrapper = new LambdaQueryWrapper<HcCommodity>()
                .eq(HcCommodity::getMerchantId, param.getId())
                .eq(HcCommodity::getUpFlag, HcUpFlagEnum.YES)
                .last("order by SORT is null, SORT, ID");

        if (StringUtils.isNotBlank(param.getStoreName())) {
            queryWrapper.like(HcCommodity::getTradeName, param.getStoreName());
        }

        List<HcCommodity> hcCommodityList = hcCommodityService.list(queryWrapper);

        HcMerchantCommission hcMerchantCommission = hcMerchantCommissionService.getOne(new LambdaQueryWrapper<HcMerchantCommission>()
                .eq(HcMerchantCommission::getAddressId, param.getAddressId())
                .eq(HcMerchantCommission::getMerchantId, param.getId())
        );

        for (HcCommodity hcCommodity : hcCommodityList) {
            hcShoppingCartService.setShoppingCartCount(hcCommodity, sysUser.getId());
            hcCommodityService.setInformation(hcCommodity, hcMerchantCommission);
        }

        return hcCommodityList;
    }

    public IPage<HcMerchant> getList(Page<HcMerchant> page, HcMerchant param) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        IPage<HcMerchant> listByMainCategories = new Page<>();

//        long start = System.currentTimeMillis();
        HcSiteAddressDetails hcSiteAddressDetails = hcSiteAddressDetailsService.getById(param.getAddressId());
//        log.info("消耗时间1：" + (System.currentTimeMillis() - start) + "毫秒");

        if (hcSiteAddressDetails == null) {
            throw new JeecgBootException("未查询到地址信息，请重新选择地址");
        }

        param.setSiteId(hcSiteAddressDetails.getSiteId());

        if (StringUtils.isNotBlank(param.getStoreName())) {
            //如果有搜索内容
            //先搜索菜品
            List<HcCommodity> list = hcCommodityMapper.getList(new HcCommodity().setTradeName(param.getStoreName()));

            //再根据菜品的商户id和商户名称去搜索商户
            List<String> ids = list.stream().map(HcCommodity::getMerchantId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(ids)) {
                param.setIds(ids);
            }
            listByMainCategories = hcMerchantMapper.getList(page, param);

            for (HcMerchant record : listByMainCategories.getRecords()) {
                //根据商户id把之前查出来的菜品set进去
                List<HcCommodity> hcCommodityList = list.stream().filter(hcCommodity -> hcCommodity.getMerchantId().equals(record.getId())).limit(6).collect(Collectors.toList());

                //如果没查到匹配菜品，则去查询商户下面所有的菜品set进去
                if (CollectionUtils.isEmpty(hcCommodityList)) {
                    hcCommodityList = hcCommodityService.list(new LambdaQueryWrapper<HcCommodity>()
                            .eq(HcCommodity::getMerchantId, record.getId())
                            .eq(HcCommodity::getUpFlag, HcUpFlagEnum.YES)
//                            .last("order by SORT is null, SORT, ID limit 6")
                            .last("order by SORT is null, SORT, ID")//默认展示6个修改为展示全部
                    );
                }

                HcMerchantCommission hcMerchantCommission = hcMerchantCommissionService.getOne(new LambdaQueryWrapper<HcMerchantCommission>()
                        .eq(HcMerchantCommission::getAddressId, param.getAddressId())
                        .eq(HcMerchantCommission::getMerchantId, record.getId())
                );

                for (HcCommodity hcCommodity : hcCommodityList) {
                    hcShoppingCartService.setShoppingCartCount(hcCommodity, sysUser.getId());
                    hcCommodityService.setInformation(hcCommodity, hcMerchantCommission);
                }

                record.setHcCommodityList(hcCommodityList);
            }
        } else {
//            long start2 = System.currentTimeMillis();
            listByMainCategories = hcMerchantMapper.getList(page, param);
//            log.info("消耗时间2：" + (System.currentTimeMillis() - start2) + "毫秒");

            long start4 = System.currentTimeMillis();

            for (HcMerchant record : listByMainCategories.getRecords()) {
                List<HcCommodity> hcCommodityList = hcCommodityService.list(new LambdaQueryWrapper<HcCommodity>()
                        .eq(HcCommodity::getMerchantId, record.getId())
                        .eq(HcCommodity::getUpFlag, HcUpFlagEnum.YES)
//                        .last("order by SORT is null, SORT, ID limit 6")
                        .last("order by SORT is null, SORT, ID")//默认展示6个修改为展示全部
                );

                HcMerchantCommission hcMerchantCommission = hcMerchantCommissionService.getOne(new LambdaQueryWrapper<HcMerchantCommission>()
                        .eq(HcMerchantCommission::getAddressId, param.getAddressId())
                        .eq(HcMerchantCommission::getMerchantId, record.getId())
                );
//                long start3 = System.currentTimeMillis();

                List<HcCommodity> hcCommodityListResult = new ArrayList<>();

                for (HcCommodity hcCommodity : hcCommodityList) {
//                    long start31 = System.currentTimeMillis();
                    hcShoppingCartService.setShoppingCartCount(hcCommodity, sysUser.getId());
//                    HcCommodity commodity = JSON.parseObject(redisUtil.get(RedisConstant.HC_COMMODITY + hcCommodity.getId() + "_" + hcMerchantCommission.getId()).toString(), HcCommodity.class);
//                    log.info("消耗时间3.1：" + (System.currentTimeMillis() - start31) + "毫秒");
//                    long start32 = System.currentTimeMillis();
//                    hcShoppingCartService.setShoppingCartCount(commodity, sysUser.getId());
                    hcCommodityService.setInformation(hcCommodity, hcMerchantCommission);
//                    log.info("消耗时间3.2：" + (System.currentTimeMillis() - start32) + "毫秒");

//                    hcCommodityListResult.add(commodity);
                }

//                record.setHcCommodityList(hcCommodityListResult);
//
//                for (HcCommodity hcCommodity : hcCommodityList) {
//                    hcShoppingCartService.setShoppingCartCount(hcCommodity, sysUser.getId());
//                    hcCommodityService.setInformation(hcCommodity, hcMerchantCommission);
//                }
//                log.info("消耗时间3：" + (System.currentTimeMillis() - start3) + "毫秒");
//                log.info("商品数量：" + hcCommodityList.size());
                record.setHcCommodityList(hcCommodityList);
            }

//            log.info("消耗时间4：" + (System.currentTimeMillis() - start4) + "毫秒");
        }

//        long start5 = System.currentTimeMillis();
        List<HcMerchant> records = listByMainCategories.getRecords();
        if (!CollectionUtils.isEmpty(records)){
            List<HcMerchant> recordsToRemoveList = new ArrayList<>();
            for (HcMerchant record : records) {

                //llj 添加了商户对大厦的供餐时间和是否对大厦供餐，所以此出需要过滤掉商户和大厦关系表（hc_address_merchant_relation）中为false的商户的id
                HcAddressMerchantRelation hcAddressMerchantRelation = addressMerchantRelationMapper.selectOne(new LambdaQueryWrapper<HcAddressMerchantRelation>()
                        .eq(HcAddressMerchantRelation::getMerchantId, record.getId()).eq(HcAddressMerchantRelation::getAddressDetailsId, param.getAddressId()));
                if (null!=hcAddressMerchantRelation){
                    //对应大厦的供餐时间
                    JSONArray jsonArray = JSON.parseArray(record.getBusinessHours());
                    JSONObject first = (JSONObject) jsonArray.get(0);
                    first.put("startTime",hcAddressMerchantRelation.getProvideStartTime());
                    first.put("endTime",hcAddressMerchantRelation.getProvideEndTime());
                    for (int i = 1; i < jsonArray.size(); i++) {
                        JSONObject obj = (JSONObject) jsonArray.get(i);
                        obj.put("startTime", "");
                        obj.put("endTime", "");
                    }
                    record.setBusinessHours(jsonArray.toJSONString());
                }
                if (null!=hcAddressMerchantRelation && hcAddressMerchantRelation.getIsOpen().equals("false")){
                    recordsToRemoveList.add(record);
                }
                this.checkBusinessState(record);
            }
            records.removeAll(recordsToRemoveList);
            listByMainCategories.setRecords(records);
            listByMainCategories.setSize(records.size());
        }
//        log.info("消耗时间5：" + (System.currentTimeMillis() - start5) + "毫秒");
        return listByMainCategories;
    }

    @Override
    public JSONObject transferToMerchant(String openId, BigDecimal amount,String outNo,String remarks) throws Exception {
        //转账金额
        BigDecimal transfer_amount = amount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP);
        //商户号
        String mchid = "1635890587";
        //申请商户号的appid或商户号绑定的appid（企业号corpid即为此appid）
        String appId = "wx50c118fbe2e4490f";
        //用户在直连商户应用下的用户标示
//        String openId = accessToken.getOpenId();
        //商户证书编号
        String wechatPayserialNo = "3211021750A9B797F90787395247194D1F886032";
        //商户证书路径（在你本机测试时放你本机路径中的就可以）
//        String privatekeypath = "E:\\workspace\\yong_shan_tuan\\yst_\\jeecg-boot\\jeecg-boot-module-system\\src\\main\\resources\\wx\\apiclient_key.pem";

        Map<String, Object> postMap = new HashMap<String, Object>();

        postMap.put("appid", appId);
        System.out.println("appid:" + appId);
        postMap.put("out_batch_no", outNo);
        //该笔批量转账的名称
        postMap.put("batch_name", "结算");
        //转账说明，UTF8编码，最多允许32个字符
        postMap.put("batch_remark","结算");
        //转账金额单位为“分”。 总金额
        postMap.put("total_amount", transfer_amount);
        //。转账总笔数
        postMap.put("total_num", 1);


        List<Map> list = new ArrayList<>();
        Map<String, Object> subMap = new HashMap<>(4);
        //商家明细单号 该商家下唯一
        subMap.put("out_detail_no", outNo);
        //转账金额
        subMap.put("transfer_amount",transfer_amount);
        //转账备注
        subMap.put("transfer_remark", remarks);
        //用户在直连商户应用下的用户标示
        subMap.put("openid", openId);
        //大金额需要传入真实姓名
//        subMap.put("user_name", RsaCryptoUtil.encryptOAEP(userName,VechatPayV3Util.getSaveCertificates(privatekeypath)));
        list.add(subMap);
        postMap.put("transfer_detail_list", list);

        //发起转账操作
        String result = HttpUtil.postTransBatRequest(
                "https://api.mch.weixin.qq.com/v3/transfer/batches",
                JSONObject.toJSONString(postMap),
                wechatPayserialNo,
                mchid,
                privatekeypath,
                "/v3/transfer/batches");
        System.out.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }

    @Override
    public JSONObject transferToMerchant2000(String openId, BigDecimal amount,String outNo,String remarks,String userName) throws Exception {
        //转账金额
        BigDecimal transfer_amount = amount.multiply(new BigDecimal(100)).setScale(0, BigDecimal.ROUND_HALF_UP);
        //商户号
        String mchid = "1635890587";
        //申请商户号的appid或商户号绑定的appid（企业号corpid即为此appid）
        String appId = "wx50c118fbe2e4490f";
        //用户在直连商户应用下的用户标示
//        String openId = accessToken.getOpenId();
        //商户证书编号
        String wechatPayserialNo = "3211021750A9B797F90787395247194D1F886032";



        //商户证书路径（在你本机测试时放你本机路径中的就可以）
        String privatekeypath = "E:\\workspace\\yong_shan_tuan\\yst_\\jeecg-boot\\jeecg-boot-module-system\\src\\main\\resources\\wx\\apiclient_key.pem";
        //商户证书路径（在你本机测试时放你本机路径中的就可以）
        String privateCertPath = "E:\\workspace\\yong_shan_tuan\\yst_\\jeecg-boot\\jeecg-boot-module-system\\src\\main\\resources\\wx\\apiclient_cert.pem";


        Map<String, Object> postMap = new HashMap<String, Object>();

        postMap.put("appid", appId);
        System.out.println("appid:" + appId);
        postMap.put("out_batch_no", outNo);
        //该笔批量转账的名称
        postMap.put("batch_name", "结算");
        //转账说明，UTF8编码，最多允许32个字符
        postMap.put("batch_remark","结算");
        //转账金额单位为“分”。 总金额
        postMap.put("total_amount", transfer_amount);
        //。转账总笔数
        postMap.put("total_num", 1);

        List<Map> list = new ArrayList<>();
        Map<String, Object> subMap = new HashMap<>(4);
        //商家明细单号 该商家下唯一
        subMap.put("out_detail_no", outNo);
        //转账金额
        subMap.put("transfer_amount",transfer_amount);
        //转账备注
        subMap.put("transfer_remark", remarks);
        //用户在直连商户应用下的用户标示
        subMap.put("openid", openId);
        //大金额需要传入真实姓名
//        subMap.put("user_name", RsaCryptoUtil.encryptOAEP(userName,VechatPayV3Util.getSaveCertificates(privateCertPath)));
        list.add(subMap);
        postMap.put("transfer_detail_list", list);

        //发起转账操作
        String result = HttpUtil.postTransBatRequest(
                "https://api.mch.weixin.qq.com/v3/transfer/batches",
                JSONObject.toJSONString(postMap),
                wechatPayserialNo,
                mchid,
                privatekeypath,
                "/v3/transfer/batches");
        JSONObject jsonObject = JSONObject.parseObject(result);
        return jsonObject;
    }


    @Override
    public List<HcMerchant> getAllAutoSettleMerchant() {
        return hcMerchantMapper.getAllAutoSettleMerchant();
    }

    @Override
    public Integer changeAutoSettle(String merchantId, Boolean autoSettle) {
        return hcMerchantMapper.changeAutoSettle(merchantId,autoSettle);
    }

    @Override
    public Integer clearMerchantOpenId(String merchantId) {
        return hcMerchantMapper.clearMerchantOpenId(merchantId);
    }
}

